package com.justnow.offer;

public class Solution12 {
    public boolean exist(char[][] board, String word) {
        char[] words = word.toCharArray();

        for (int i = 0; i < board.length; i++) {
            for (int j = 0; j < board[0].length; j++) {
                if (dfs(board, words, i, j, 0)) return true;
            }
        }
        return false;
    }

    private boolean dfs(char[][] board, char[] words, int i, int j, int k) {
        if (i >= board.length || i < 0 || j >= board[0].length || j < 0 || board[i][j] != words[k]) //i或者j越界，矩阵与字符串中数据不相同，需要直接返回false
            return false;
        if (k == words.length - 1) return true; //如果为words最后一个字符的下标，那么返回true
        char tmp = board[i][j]; //将i行j列中的元素，赋值给tmp
        board[i][j] = '/'; // 修改坐标为(i, j)为'/'表示已经被访问过了，因为默认words中的字符属于英文字母，所以回溯到这个坐标下的元素肯定返回false
        boolean res = dfs(board, words, i + 1, j, k + 1) || dfs(board, words, i - 1, j, k + 1)
                || dfs(board, words, i, j + 1, k + 1) || dfs(board, words, i, j - 1, k + 1);
        board[i][j] = tmp;  //上一行计算完res之后，需要将坐标为(i, j)的元素还原，
        return res;
    }

    /**
     * 方法二
     * @param board
     * @param word
     * @return
     */



}
